// pages/admin/user-management.js
const { UserManager, UserRole, Permissions } = require('../../models/user.js');

Page({
  data: {
    users: [],
    currentUser: null,
    isAdmin: false,
    roles: [
      { id: UserRole.USER, name: '普通用户' },
      { id: UserRole.ADMIN, name: '管理员' }
    ],
    editingUser: null,
    showEditModal: false
  },

  onLoad: function() {
    this.checkAdminPermission();
  },
  
  onShow: function() {
    this.loadUsers();
  },

  // 检查管理员权限
  checkAdminPermission: function() {
    const app = getApp();
    const userInfo = app.globalData.userInfo;
    const userRole = app.globalData.userRole;
    
    if (!userInfo) {
      wx.redirectTo({
        url: '/pages/login/index'
      });
      return;
    }
    
    this.setData({
      currentUser: userInfo,
      isAdmin: userRole === UserRole.ADMIN
    });
    
    if (userRole !== UserRole.ADMIN) {
      wx.showModal({
        title: '权限不足',
        content: '只有管理员可以访问此页面',
        showCancel: false,
        success: () => {
          wx.navigateBack();
        }
      });
    }
  },

  // 加载用户列表
  loadUsers: function() {
    const userManager = new UserManager();
    const users = userManager.getUsers();
    
    this.setData({
      users: users.map(user => ({
        ...user,
        roleName: this.getRoleName(user.role)
      }))
    });
  },

  // 获取角色名称
  getRoleName: function(roleId) {
    const role = this.data.roles.find(r => r.id === roleId);
    return role ? role.name : '未知';
  },

  // 打开编辑模态框
  showEditUser: function(e) {
    const userId = e.currentTarget.dataset.id;
    const user = this.data.users.find(u => u.id === userId);
    
    if (user) {
      this.setData({
        editingUser: user,
        showEditModal: true
      });
    }
  },

  // 关闭编辑模态框
  closeEditModal: function() {
    this.setData({
      showEditModal: false,
      editingUser: null
    });
  },

  // 角色选择变化
  roleChange: function(e) {
    const roleId = parseInt(e.detail.value);
    this.setData({
      'editingUser.role': roleId,
      'editingUser.roleName': this.getRoleName(roleId)
    });
  },

  // 保存用户编辑
  saveUserEdit: function() {
    const { editingUser } = this.data;
    
    if (!editingUser) return;
    
    const userManager = new UserManager();
    userManager.updateUser(editingUser.id, {
      role: editingUser.role
    });
    
    wx.showToast({
      title: '更新成功',
      icon: 'success'
    });
    
    this.closeEditModal();
    this.loadUsers();
  },

  // 删除用户
  deleteUser: function(e) {
    const userId = e.currentTarget.dataset.id;
    const user = this.data.users.find(u => u.id === userId);
    
    if (!user) return;
    
    // 不能删除自己
    if (user.id === this.data.currentUser.id) {
      wx.showToast({
        title: '不能删除自己',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除用户 ${user.realName || user.nickName} 吗？`,
      success: (res) => {
        if (res.confirm) {
          const userManager = new UserManager();
          userManager.deleteUser(userId);
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
          
          this.loadUsers();
        }
      }
    });
  },

  // 添加新用户（跳转到登录页面）
  addNewUser: function() {
    wx.navigateTo({
      url: '/pages/login/index'
    });
  },

  // 返回上一页
  navigateBack: function() {
    wx.navigateBack();
  }
});